import axios from 'axios'
import QS from 'qs';
import Config from '../config/app.js'
import {
	Notification,
	Loading
} from 'element-ui';


import {
	getToken,
	setToken,
	removeToken
} from '../utils/dataStorage.js'

axios.defaults.baseURL = Config.apiUrl + '/' + Config.apiPrefix;
axios.defaults.timeout = Config.timeout;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
axios.defaults.retry = Config.requestRetry;
axios.defaults.retryDelay = Config.requestRetryDelay;


axios.interceptors.request.use(
	config => {
		if (!config.closeLoading) {
			//window.loadingInstance = Loading.service();
		}
		config.headers[Config.tokenKey] = getToken();
		config.url = config.url.indexOf('http://') == -1 ? Config.apiUrl + config.url : config.url;
		// let noParameters = config.url.indexOf('?') == -1;
		// config.url = noParameters ? config.url + '?access_token=' + getToken() : config.url + '&access_token=' + getToken();
		return config
	},
	error => {
		Promise.reject(error)
	}
)



axios.interceptors.response.use(
	response => { //Grade
		if (!response.config.closeLoading) {
			setTimeout(_ => {
				// window.loadingInstance.close();
			}, 400);
		}
		const res = response
		if (res.status !== 200) {
			Notification({
				title: '数据返回出错',
				message: "请稍后重试",
				type: 'warning'
			});
			return Promise.reject('error')
		} else {
			if ((response.config).hasOwnProperty('closeInterceptors') && response.config.closeInterceptors) {
				return res.data
			}

			if (res.data.code > 10000 && getToken()) {
				Notification({
					title: '登录状态',
					message: "登录状态失效，请稍后重试",
					type: 'warning'
				});
				removeToken();
				window.location.href = '/login';
			} else if (res.data.code != 200) {
				Notification({
					title: res.data.message,
					type: 'warning'
				});
				if (res.data.code == 402) { //登录状态失效
					removeToken();
					setTimeout(_ => {
						window.location.href = '/login';
					}, 2000)
				}
				return Promise.reject('error');
			}
			if (res.headers[Config.tokenKey]) {
				setToken(res.headers[Config.tokenKey]);
			}
			return res.data.data
		}
	},
	error => {
		console.log(error)
		setTimeout(_ => {
			window.loadingInstance.close();
		}, 300)
		Notification({
			title: "请求未响应",
			message: "服务器可能出了点问题",
			type: 'warning'
		});
		return Promise.reject(error) //千万不能去掉，，，否则请求超时会进入到then方法，导致逻辑错误。
	}
)


export default axios
